package me.firstapp.bbs.controller.interceptor;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import me.firstapp.common.module.bbs.JsonMember;
import me.firstapp.common.utils.CookieUtils;
import me.firstapp.common.utils.SpringContextTool;
import me.firstapp.common.utils.StrUtils;

public class PageInterceptor implements HandlerInterceptor {

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e)
			throws Exception {

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj,
			ModelAndView modelAndView) throws Exception {

	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		// 解决中文乱码
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		request.setAttribute("ctx", request.getContextPath());
		request.setAttribute("pageUrl", request.getRequestURL().toString());

		Cookie cookie = CookieUtils.getCookieByName(request, "loginToken");
		if(cookie != null){
			String loginToken = cookie.getValue();
			if (StrUtils.isNotNULL(loginToken)) {
				ApplicationContext applicationContext = SpringContextTool.getApplicationContext();
				@SuppressWarnings("unchecked")
				RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) applicationContext
						.getBean("redisTemplate");
				JsonMember member = (JsonMember) redisTemplate.opsForValue().get("login_member_" + loginToken);
				if (member != null) {
					request.setAttribute("member", member);
					redisTemplate.expire("login_member_" + loginToken, 30, TimeUnit.MINUTES);// 登录有效期重置为30分钟
				}

			}
		}

		return true;
	}

}
